/**
 * Copyright 2019 吉鼎科技.
 *
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.task.zkex.simple;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.type.FieldVo;
import cn.easyplatform.web.ext.PairItem;
import cn.easyplatform.web.ext.Widget;
import cn.easyplatform.web.ext.zul.ChosenboxExt;
import cn.easyplatform.web.task.OperableHandler;
import cn.easyplatform.web.task.event.EventListenerHandler;
import cn.easyplatform.web.task.zkex.ListSupport;
import cn.easyplatform.web.utils.PageUtils;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.*;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;

import java.util.List;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class ChosenboxBuilder extends AbstractQueryBuilder<ChosenboxExt> implements Widget {

    public ChosenboxBuilder(OperableHandler mainTaskHandler, ChosenboxExt comp) {
        super(mainTaskHandler, comp);
    }

    public ChosenboxBuilder(ListSupport support, ChosenboxExt comp, Component anchor) {
        super(support, comp, anchor);
    }

    @Override
    public Component build() {
        PageUtils.checkAccess(main.getAccess(), me);
        me.setAttribute("$proxy", this);
        Object value = me.getValue();
        if (me.isImmediate()) {
            load();
            me.setValue(value);
        }
        if (!Strings.isBlank(me.getEvent())) {
            if (me.isCreatable()) {
                me.addEventListener("onSearch", (EventListener<InputEvent>) event -> {
                    ListModel<PairItem> model = me.getModel();
                    PairItem item = new PairItem(event.getValue());
                    ((ListModelList<PairItem>) model).add(item);
                    me.addItemToSelection(item);
                    EventListenerHandler elh = new EventListenerHandler("onSearch", main, me.getEvent(), anchor);
                    elh.onEvent(new Event(Events.ON_CREATE, me, item));
                });
            }
            me.addEventListener("onSelect", (EventListener<SelectEvent>) event -> {
                if (event.getUnselectedObjects() != null && !event.getUnselectedObjects().isEmpty()) {
                    PairItem[] items = new PairItem[1];
                    event.getUnselectedObjects().toArray(items);
                    EventListenerHandler elh = new EventListenerHandler("onRemove", main, me.getEvent(), anchor);
                    elh.onEvent(new Event("onRemove", me, items[0]));
                } else if (!event.getSelectedObjects().isEmpty()) {
                    event.getSelectedObjects().removeAll(event.getPreviousSelectedObjects());
                    PairItem[] items = new PairItem[1];
                    event.getSelectedObjects().toArray(items);
                    EventListenerHandler elh = new EventListenerHandler("onSelect", main, me.getEvent(), anchor);
                    elh.onEvent(new Event("onSelect", me, items[0]));
                }
            });
        }
        return me;
    }

    protected void createModel(List<?> data) {
        ListModelList<PairItem> model = new ListModelList<PairItem>();
        for (Object fv : data) {
            PairItem item = null;
            Object[] fvs = (Object[]) fv;
            boolean isRaw = !(fvs[0] instanceof FieldVo);
            if (fvs.length == 1) {
                item = new PairItem(isRaw ? fvs[0] : ((FieldVo) fvs[0]).getValue());
            } else if (fvs.length > 1) {
                item = new PairItem(isRaw ? fvs[0] : ((FieldVo) fvs[0]).getValue(),
                        isRaw ? (String) fvs[1] : (String) ((FieldVo) fvs[1]).getValue());
            }
            model.add(item);
        }
        me.setModel(model);
    }

    @Override
    public void reload(Component me) {
        me.getChildren().clear();
        load();
    }

}
